package fh.app4stud.mensa;

import android.app.Activity;
import android.content.*;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import fh.app4stud.mensa.activities.MenusTabWidget;
import fh.app4stud.mensa.activities.SettingsPreferences;
import fh.app4stud.mensa.data.RestaurantLocation;

import java.util.ArrayList;
import java.util.Calendar;

/**
 * Main class, first activty. starts the location service and menu service.
 * It passes the data sets to Activiteis like MenuTab, LocationSettings..ect
 *
 * Created by IntelliJ IDEA.
 * User: ivan plese
 * Date: 22.04.11
 * Time: 00:19
 * To change this template use File | Settings | File Templates.
 */


public class Start extends Activity {

    private MensaMenuService mensaMenuService;
    private MensaLocationService mensaLocationService;
    private SharedPreferences preference;
    private ArrayList<String> preferredLocations;

    private Button showMenu;
    private Spinner locationsSpinner;
    private TextView startMessage;

    private boolean mensaLocationBound;
    private boolean mensaMenuBound;
    private boolean firstLoad = true;

    static final private int MENU_ITEM_CURRENT_LOC = Menu.FIRST;
    static final private int MENU_ITEM_SETTINGS = Menu.FIRST+1;
    private static String TAG = "START CLASS";

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        Log.i(TAG, "in onCreate()");

        setContentView(R.layout.main);
        ArrayList<RestaurantLocation> locationsList = new ArrayList<RestaurantLocation>();
        preferredLocations = new ArrayList<String>();

        startServices();

        //Shared preferences
        Context context = getApplicationContext();
        preference = PreferenceManager.getDefaultSharedPreferences(context);

        //initiate views
        locationsSpinner = (Spinner) findViewById(R.id.start_spinner_locations);
        showMenu = (Button)findViewById(R.id.show_menu_button);
        startMessage = (TextView)findViewById(R.id.start_message);

        //add some preferences for testing purpose
        savePreferences();
        updatePreferredLocations();

        hookUpButtons();
        hookUpEvents();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, " in onStop()");
        // Unbind from the service
        if (mensaLocationBound) {
            unbindService(locationConnection);
            mensaLocationBound = false;
        }
        if(mensaMenuBound){
            unbindService(menuConnection);
            mensaMenuBound = false;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        saveState();
    }

    @Override
    protected void onResume() {
        super.onResume();
        updatePreferredLocations();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        saveState();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        super.onCreateOptionsMenu(menu);

        int groupId = 0;
        //order position of the item
        int menuOrder = Menu.NONE;
        //create menu item and save a refference to it
        //MenuItem menuItem_home = menu.add(groupId, MENU_ITEM_CURRENT_LOC, menuOrder, R.string.start_menu_current_loc);
        MenuItem menuItem_settings = menu.add(groupId, MENU_ITEM_SETTINGS, menuOrder, R.string.start_menu_settings);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem){
        super.onOptionsItemSelected(menuItem);
        switch (menuItem.getItemId()){
            case MENU_ITEM_CURRENT_LOC:
                //TODO go to current locations detail page
                return true;
            case MENU_ITEM_SETTINGS:
                Intent locationsSettingsIntent = new Intent(this, SettingsPreferences.class);
                startActivity(locationsSettingsIntent);
                return true;
        }
        return false;
    }

    private void hookUpEvents() {

        Log.i(TAG, "HookUpEvents()");
        locationsSpinner.setOnItemSelectedListener(

                new AdapterView.OnItemSelectedListener() {

                    public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
                        String currentLoc = adapter.getItemAtPosition(i).toString();
                        //set the chosen location as current location
                        SharedPreferences.Editor editor = preference.edit();
                        editor.putString(SettingsPreferences.CURRENT_LOCATION, currentLoc);
                        editor.commit();
                    }

                    public void onNothingSelected(AdapterView arg0) {
                        //clear tab vies if already created
                    }
                });
    }

    private void hookUpButtons() {

        Log.i(TAG, "HookUpButtons()");
        showMenu.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //call tab widget
                String currentLoc = preference.getString(SettingsPreferences.CURRENT_LOCATION, "");
                Intent getMenu = new Intent(Start.this, MenusTabWidget.class);
                //send the current location and day trough bundle
                getMenu.putExtra(SettingsPreferences.CURRENT_LOCATION, currentLoc);
                getMenu.putExtra(SettingsPreferences.CURRENT_DAY, getCurrentDay());
                startActivity(getMenu);

            }
        });
    }

    private void savePreferences() {

        //TODO on the first installation let user set it
        SharedPreferences.Editor editor = preference.edit();
        editor.putFloat(SettingsPreferences.CURRENT_LATITUDE, 47.078364F);
        editor.putFloat(SettingsPreferences.CURRENT_LONGITUDE, 15.451412F);
        //editor.putString(SettingsPreferences.PREF_LOCATION1, "Uni Graz Mensa WALLerie");
        //editor.putString(SettingsPreferences.PREF_LOCATION2, "Mensa Kapfenberg");
        editor.putInt(SettingsPreferences.CURRENT_DAY, getCurrentDay());
        editor.commit();
    }

    private void updatePreferredLocations() {

        //TODO show the distance of each location from the user
        //clear old values from preferred location list and populate with
        //current from context preferences
        preferredLocations.clear();
        java.util.Map<String, ?> allPref = preference.getAll();
        for(String s : SettingsPreferences.PREFEREDLOCATIONSARRAY){
            String str = (String)allPref.get(s);
            if(str != "" && str != null){
                preferredLocations.add(str);
            }
        }
        if(!preferredLocations.isEmpty()) firstLoad = false;

        if(firstLoad){
           locationsSpinner.setVisibility(View.GONE);
           showMenu.setVisibility(View.GONE);
            startMessage.setVisibility(View.VISIBLE);
        }
        else {
            locationsSpinner.setVisibility(View.VISIBLE);
            showMenu.setVisibility(View.VISIBLE);
            startMessage.setVisibility(View.GONE);
        }

        //setting up spinner with preferred locations
        String mCurrent = preference.getString(SettingsPreferences.CURRENT_LOCATION, "");
        int setIndex = preferredLocations.indexOf(mCurrent);


        ArrayAdapter<String> preferredLocationsAA = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, preferredLocations);
        preferredLocationsAA.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        locationsSpinner.setAdapter(preferredLocationsAA);
        if(setIndex > 0){
            //set the selected item in the spinner on current location
            locationsSpinner.setSelection(setIndex);

        }

    }

    public static int getCurrentDay(){
        //if it is sunday it returns 1
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_WEEK);
        if(day == 1 || day == 7){
            day = 2;
        }
        return day;
    }

    private void startServices() {

        Log.i(TAG, "Staring the services");

        // Bind to MensaLocationService
        Intent locationIntent = new Intent(this, MensaLocationService.class);
        startService(locationIntent);
        bindService(locationIntent, locationConnection, Context.BIND_AUTO_CREATE);

         // Bind to MensaMenuService
         Intent menuIntent = new Intent(this, MensaMenuService.class);
            startService(menuIntent);
            bindService(menuIntent, menuConnection, Context.BIND_AUTO_CREATE);

        //on sunday update the menu
        if(getCurrentDay() == 1){
            // Bind to MensaMenuService
            //Intent menuIntent = new Intent(this, MensaMenuService.class);
            //startService(menuIntent);
            //bindService(menuIntent, menuConnection, Context.BIND_AUTO_CREATE);
        }
    }

    private void saveState(){
        if(firstLoad) return;
        String s = locationsSpinner.getSelectedItem().toString();
        SharedPreferences.Editor editor = preference.edit();
        editor.putString(SettingsPreferences.CURRENT_LOCATION, s);

    }

    private ServiceConnection locationConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            //we've bound to local service, cast the Ibinder and get localSErvice instance
            MensaLocationService.LocalBinder binder = (MensaLocationService.LocalBinder) iBinder;
            mensaLocationService = binder.getLocationService();
            mensaLocationBound = true;
        }

        public void onServiceDisconnected(ComponentName componentName) {

            mensaLocationBound = false;

        }
    };

    private ServiceConnection menuConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

            //we've bound to local service, cast the Ibinder and get localService instance
            MensaMenuService.MensaBinder binder = (MensaMenuService.MensaBinder) iBinder;
            mensaMenuService = binder.getMensaMenuService();
            mensaMenuBound = true;

        }

        public void onServiceDisconnected(ComponentName componentName) {

            mensaMenuBound = false;

        }
    };

    public void MessageBox(String message){
                Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }
    /*if(firstLoad) {
            MessageBox();
            return;
        }*/

}
